import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class Leetcode15 {
    public static void main(String[] args) {
        int k[] = {-2, 0, 1, 1, 2};
        System.out.println(threeSum(k));
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        int numsLength = nums.length;
        Arrays.sort(nums);

        for (int i = 0; i < numsLength; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            int left = i + 1;
            int right = numsLength - 1;
            while (right > left) {
                if (nums[i] + nums[left] + nums[right] == 0) {
                    list.add(List.of(nums[i], nums[left], nums[right]));
                    left++;
                    right--;
                    while (right > left && nums[left] == nums[left - 1]) {
                        left++;
                    }
                    while (right > left && nums[right] == nums[right + 1]) {
                        right--;
                    }
                } else if (nums[left] + nums[right] > -nums[i]) {
                    right--;
                } else {
                    left++;
                }
            }
        }

        return list;
    }
}
